import axios, { AxiosRequestConfig, AxiosError } from 'axios';
import { notification } from 'antd';
import identification from '@/components/Identification';
import { redirectLoginPage, redirectOauthLoginPage } from 'utils/utils';
import createError from './createError';

import codeMessage from './codeMessage';

const defaultErrorCode = 500;

/**
 * 在 Response 添加一个 errorType 用来区分 "http请求异常" 和 "业务异常"
 * */
export interface IException extends AxiosError {
  errorType: 'httpError' | 'serviceError';
}

/**
 * 给 requestConfig 添加两个入参
 * @getOriginResponse: 是否获取原始的 axios response 响应对象
 * @errorHandler: 自定义异常处理方法，用来覆盖默认的异常处理
 * */
export interface IRequestOptions extends AxiosRequestConfig {
  getOriginResponse?: boolean;
  errorHandler?: (e: IException) => void;
}

const defaultOption: IRequestOptions = {
  method: 'GET',
  getOriginResponse: false,
  errorHandler: (error: IException): void => {
    const { response, message } = error;
    if (response && response.status) {
      const { status } = response;
      let errorText = '';
      if (error.errorType === 'httpError') {
        // @ts-ignore
        errorText = codeMessage[response.status] || response.statusText;
        // 401 的状态下不显示错误信息
        if (status !== 401) {
          notification.error({
            message: `请求错误 ${status}`,
            description: errorText,
          });
        }
      } else if (message?.includes('timeout')) {
        errorText = '请求超时';
      } else {
        errorText = response?.data?.error || '未知错误';

        // notification.error({
        //   message: `请求错误 ${error.code}`,
        //   description: errorText,
        // });
      }
    } else if (!response) {
      notification.error({
        message: '请求错误 -2',
        description: '网络异常',
      });
    }
  },
};

/** 创建一个 axios 实例 */
const instance = axios.create();
instance.defaults.timeout = 100000; // 100000

export default async function request(option: IRequestOptions): Promise<any> {
  const newOption = {
    ...defaultOption,
    ...option,
  };

  try {
    const response = await instance.request(newOption);
    const { data: responseData } = response;

    const { code } = responseData;

    if (code !== 0) {
      if (newOption.errorHandler) {
        newOption.errorHandler(createError(response));
      }
    }
    if (newOption.getOriginResponse) {
      return Promise.resolve(response);
    }
    return Promise.resolve({
      code: 0,
      data: null,
      error: '',
      ...responseData,
    });
  } catch (error) {
    const { response, message } = error;

    let errorText = '请求失败';

    if (response?.status) {
      // @ts-ignore
      errorText = codeMessage[response.status] || response.statusText;
    }
    if (message?.includes('timeout')) {
      errorText = '请求超时';
    }

    switch (response?.status) {
      case 401:
        // const feedbackCode = await identification.appear();
        // if (feedbackCode === 1) {
        //   identification.remove();

        //   // 登录成功后，重发之前失败的请求
        //   // 请注意，这是一个带 promise 的递归调用，逻辑有点绕，要改之前先要把逻辑搞清楚
        //   const res = await request(option);
        //   return Promise.resolve(res);
        // } else {
        //   if (newOption.errorHandler) {
        //     newOption.errorHandler({
        //       ...error,
        //       errorType: 'httpError',
        //     });
        //   }
        //   return Promise.resolve({
        //     code: error?.response?.status || defaultErrorCode,
        //     data: null,
        //     error: errorText,
        //   });
        // }
        // redirectLoginPage();
        redirectOauthLoginPage();
      default:
        if (newOption.errorHandler) {
          newOption.errorHandler({
            ...error,
            response: { data: { error: errorText } },
            errorType: 'httpError',
          });
        }

        return Promise.resolve({
          code: error?.response?.status || defaultErrorCode,
          data: null,
          error: errorText,
        });
    }
  }
}
